#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import sys
import datetime

from PyQt5.QtWidgets import  QApplication,QMainWindow,QWidget,QPushButton, QLabel, QSystemTrayIcon, QMenu, QAction
from PyQt5.QtCore import QTimer, Qt, QRect
from PyQt5.QtGui import QBitmap, QPainter, QColor, QFont, QPen, QRegion, QIcon

class MyEyeWidget(QWidget):

    def __init__(self):
        self.app = QApplication(sys.argv)
        super(MyEyeWidget, self).__init__()
        
        self.work_min = 45
        self.break_min = 5

        self.setWindowFlags(Qt.WindowStaysOnTopHint
            # | Qt.X11BypassWindowManagerHint # 这个和下面的有什么区别呢
            # | Qt.BypassWindowManagerHint
            | Qt.FramelessWindowHint
        )
        self.timer_label = QLabel(self)
        self.system_icon_set()
        self.show()

    def system_icon_set(self):
        self.sys_icon = QSystemTrayIcon()
        self.icon_prompt_str = "保护眼睛, 每%d分钟休息%d分钟, W延长工作1分钟"%(self.work_min, self.break_min)
        self.sys_icon.setToolTip(self.icon_prompt_str)
        img_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "eye-toy.jpg")
        print(img_path)
        qicon = QIcon(img_path)

        self.sys_menu = QMenu(self)
        self.reset_timer_action = QAction("reset", self, triggered=self.reset_timer)
        self.work_more_10m_action = QAction("work 10m", self, triggered=self.continue_10m)
        self.quit_action = QAction("quit", self, triggered=self.app.exit)
        self.sys_menu.addAction(self.work_more_10m_action)
        self.sys_menu.addAction(self.reset_timer_action)
        self.sys_menu.addAction(self.quit_action)
        self.sys_icon.setContextMenu(self.sys_menu)

        self.sys_icon.setIcon(qicon)
        self.sys_icon.show()
    
    def continue_10m(self):
        m_10 = 10 * 60
        if self.counter > self.start_break_counter - m_10:
            self.counter = self.start_break_counter - m_10
            self.mode = 0

    def reset_timer(self):
        print("reset timer")
        # 这两个参数应该从命令行获取
        self.start_break_counter = self.work_min * 60  # 工作时间,秒
        self.break_counter = self.break_min * 60  # 休息时间, 秒
        self.mode = 0   # 0 work_mode, 1 brek mode
        self.counter = 0

    
    def view_draw(self):
        x, y = 0, 0
        desktop = QApplication.desktop()
        width, height = desktop.width(), desktop.height()
        self.move(x, y)
        self.resize(width, height)

        # self.widget.setStyleSheet("background-color:green;")
        # self.widget.setStyleSheet("background-color:rgba(0,255,0, 1);")
        self.setStyleSheet("background-color:rgba(0,0,0, 1);")
        self.setWindowOpacity(0.8)

        self.timer_label.setWordWrap(True) # 换行设置
        self.timer_label.resize(width, height)
        self.timer_label.move(0, 0)
        self.timer_label.setAlignment(Qt.AlignCenter)

        # self.time_label.setStyleSheet("background-color: rgb(250, 0, 0);font-size:60px;color:blue");
        # self.time_label.setStyleSheet("background-color:red;font-size:14px;color:blue")
        self.timer_label.setStyleSheet("font-size:32px;color:green;")
        # self.timer_label.setText("date time")

    def week_day(self, date):
        week_day_dict = {
            0 : '周一',
            1 : '周二',
            2 : '周三',
            3 : '周四',
            4 : '周五',
            5 : '周六',
            6 : '周天',
        }
        day = date.weekday()
        return week_day_dict[day]

    def eye_protect(self):
        tt_time = datetime.datetime.now()

        show_str = "%s %s"%(
            tt_time.strftime("%Y-%m-%d\n%H:%M:%S"),
            # tt_time.strftime("%Y-%m-%d\n%H:%M"),
            self.week_day(tt_time),
        )

        self.view_draw()
        lc = self.break_counter-self.counter
        prmpt_str = "W延长一分钟\n让你的眼睛休息吧\n%02d:%02d"%(lc/60, lc%60)
        self.timer_label.setText("%s\n\n%s"%(prmpt_str, show_str))
        self.update()

    def work_mode(self):
        x, y = 0, 0
        # width, height = 100, 100
        width, height = 0, 0
        self.move(0, 0)
        self.resize(width, height)

        self.sys_icon.setToolTip("%s\n当前工作了 %02d:%02d"%(
            self.icon_prompt_str, self.counter/60, self.counter%60))
        self.update()
    
    def refresh(self):
        self.counter += 1
        if self.mode == 0 and self.counter >= self.start_break_counter:
            self.mode = 1
            self.counter = 0
        elif self.mode == 1 and self.counter >= self.break_counter:
            self.mode = 0
            self.counter = 0

        if self.mode == 0:
            self.work_mode()
        elif self.mode == 1:
            self.eye_protect()
    
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_W:
            # 延长1分钟工作时间
            self.counter = 0 if self.start_break_counter < 60 else self.start_break_counter - 60
            self.mode  = 0
            self.refresh()
            
    def start(self):
        self.reset_timer()
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.refresh)
        self.timer.start(1000) # every 30 second
        self.app.exec_()

def check_process_start():
    pid_file = "%s/.config/pyqt-eyes/pid.txt%s"%(os.environ["HOME"], os.environ["DISPLAY"])
    print(pid_file)
    force_restart = False
    if "-f" in sys.argv:
        force_restart = True
    
    try:
        os.makedirs(os.path.dirname(pid_file))
    except:
        pass

    pid = 0
    try:
        with open(pid_file, "r") as ifs:
            pid = int(ifs.read())
    except IOError:
        pass

    try:
        with open("/proc/%d/cmdline"%(pid)) as ifs:
            result = ifs.readline()
            result = result.strip()
            eee = os.path.basename(__file__)
            if result.find(eee) >= 0:
                if force_restart:
                    os.system("kill -9 %d"%(pid))
                else:
                    print("已经有一个进程启动了: %d\n"%(pid))
                    sys.exit(1)
    except IOError:
        pass

    pid = os.getpid()
    with open(pid_file, "w") as ofs:
        ofs.write("%d"%(pid))

def main():
    check_process_start()
    t = MyEyeWidget()
    t.start()

if __name__ == "__main__":
    main()
    
